package com.tofindaway.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.tofindaway.entity.User;
import com.tofindaway.service.UserServ;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	WebApplicationContext context;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init() {
		context = ContextLoader.getCurrentWebApplicationContext();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setAttribute("list", "testt");
		response.setCharacterEncoding("GBK");
		Writer writer = response.getWriter();
		UserServ userServ = (UserServ) context.getBean("userServ");
		List<User> users = userServ.getUsers();

		writer.write("<html><head><title>good morning.</title></head><body>"
				+ "<h1 style=\"color=red\">汉字哈哈</h1>");
		writer.write("<table><tr><td>用户名 </td><td>昵称</td><td>密码</td>");
		for (User user : users) {
			writer.write("<tr><td>" + user.getUsername() + "</td><td>"
					+ user.getNickname() + "</td><td>" + user.getPassword()
					+ "</td></tr>");
		}
		writer.write("</table></body></html>");
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}
}
